package jsyf.oa.web.device;


import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import jsyf.com.util.BaseUtils;
import jsyf.com.util.ExportExcel;
import jsyf.com.util.FastJsonConvert;
import jsyf.com.util.ResponseUtils;
import jsyf.oa.facade.device.DeviceSampleFacade;
import jsyf.oa.web.socket.MyWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by LT on 2018/4/14.
 */
@Api(value = "设备样机接口", description = "设备样机接口")
@Controller
@RequestMapping("/deviceSample")
public class DeviceSampleController {

    @Resource
    private DeviceSampleFacade deviceSampleFacade;
    @Autowired
    private MyWebSocketHandler myWebSocketHandler;
    @ResponseBody
    @RequestMapping(value = "/getDeviceSampleList.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "获取样机信息列表",
            notes = "获取样机信息列表 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{pageSize:2,requestPage=1}", dataType = "String", paramType = "body")
    public void getDeviceSampleList(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject results = deviceSampleFacade.getDeviceSampleList(jsonData);
        if (results != null) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjTimeRespond(results));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("未找到数据"));
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getDeviceTypeList.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "查询设备类型",
            notes = "查询设备类型 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "", dataType = "String", paramType = "body")
    public void getDeviceTypeList(HttpServletRequest request, HttpServletResponse response) {
        JSONObject JSONObj = this.deviceSampleFacade.getDeviceTypeList();
        if (null != JSONObj) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(JSONObj));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("查找失败"));
        }
    }

    @ResponseBody
    @RequestMapping(value = "/updateSample.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "修改样机信息",
            notes = "修改样机信息 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{pageSize:2,requestPage=1}", dataType = "String", paramType = "body")
    public void updateSample(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject results = deviceSampleFacade.updateSample(jsonData);
        //发送消息
        sendMessage(results.getString("message"));
        results.remove("message");
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(results));
    }

    @ResponseBody
    @RequestMapping(value = "/updateRepaymentPlan.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "修改还款信息",
            notes = "修改还款信息 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{pageSize:2,requestPage=1}", dataType = "String", paramType = "body")
    public void updateRepaymentPlan(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject results = deviceSampleFacade.updateRepaymentPlan(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(results));
    }

    @ResponseBody
    @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "添加样机入库信息",
            notes = "添加样机入库信息 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "JSONObject:''", dataType = "String", paramType = "body")
    public void add(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject results = deviceSampleFacade.add(jsonData);
        //发送消息
        sendMessage(results.getString("message"));
        results.remove("message");
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(results));
    }

    @ResponseBody
    @RequestMapping(value = "/addRepaymentPlan.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "添加还款计划信息",
            notes = "添加还款计划信息 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "JSONObject:''", dataType = "String", paramType = "body")
    public void addRepaymentPlan(HttpServletRequest request, HttpServletResponse response, @RequestBody String JsonArray) {
        JSONObject results = deviceSampleFacade.addRepaymentPlan(JsonArray);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(results));
    }
    @ResponseBody
    @RequestMapping(value = "/addDevicePartsRecords.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "添加随机配件",
            notes = "添加随机配件 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "JSONObject:''", dataType = "String", paramType = "body")
    public void addDevicePartsRecords(HttpServletRequest request, HttpServletResponse response, @RequestBody String JsonArray) {
        JSONObject results = deviceSampleFacade.addDevicePartsRecords(JsonArray);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(results));
    }
    @ResponseBody
    @RequestMapping(value = "/getSampleById.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "根据id获取样机信息",
            notes = "根据id获取样机信息",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "id:''", dataType = "String", paramType = "body")
    public void getSampleById(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject records = this.deviceSampleFacade.getSampleById(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjTimeRespond(records));
    }

    @ResponseBody
    @RequestMapping(value = "/getSampleAndRepaymentById.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "根据id获取样机和还款计划表信息",
            notes = "根据id获取样机和还款计划表信息",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "id:''", dataType = "String", paramType = "body")
    public void getSampleAndRepaymentById(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject records = this.deviceSampleFacade.getSampleAndRepaymentById(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjTimeRespond(records));
    }

    /*导出*/
    @RequestMapping(value = "/getDownByCondition.json")
    public void getDownByCondition(HttpServletResponse response, @RequestParam String companyName, @RequestParam String deviceTypeName, @RequestParam String brandName, @RequestParam String modelName, @RequestParam String state, @RequestParam String key) throws Exception {
        List<JSONObject> records = deviceSampleFacade.getByCondition(companyName, deviceTypeName, brandName, modelName, state, key);
        getDownExcel(records, response);
    }

    public void getDownExcel(List<JSONObject> jsonObjectList, HttpServletResponse response) throws Exception {
        //导出表名、列名
        String title = "样机管理信息列表";
        String[] rowsName = new String[]{"提货日期", "提货公司", "设备类型", "品牌", "型号", "序列号",
                "状态", "提货方式", "订货支持"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        for (int i = 0; i < jsonObjectList.size(); i++) {
            JSONObject jsonObject = jsonObjectList.get(i);
            System.out.println("============="+"i==="+jsonObject);
            objs = new Object[rowsName.length];
            objs[0] = jsonObject.get("pickUpDate");
            objs[1] = jsonObject.get("companyName");
            objs[2] = jsonObject.get("deviceTypeName");
            objs[3] = jsonObject.get("brandName");
            objs[4] = jsonObject.get("modelName");
            objs[5] = jsonObject.get("sequence");
            objs[6] = jsonObject.get("state");
            objs[7] = jsonObject.get("pickUpType");
            objs[8] = jsonObject.get("orderSupport");
            dataList.add(objs);
        }
        ExportExcel ex = new ExportExcel(title, rowsName, dataList, response);
        ex.export();
    }

    @ResponseBody
    @RequestMapping(value = "/removeById.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "通过id物理删除设备",
            notes = "通过id物理删除设备 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "", dataType = "String", paramType = "body")
    public void removeById(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject obj = new JSONObject();
        obj.put("isOk", this.deviceSampleFacade.removeById(jsonData));
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(obj));
    }

    @ResponseBody
    @RequestMapping(value = "/delById.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "通过id逻辑删除设备",
            notes = "通过id逻辑删除设备 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "", dataType = "String", paramType = "body")
    public void delById(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject obj = new JSONObject();
        obj.put("isOk", this.deviceSampleFacade.delById(jsonData));
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(obj));
    }

    @ResponseBody
    @RequestMapping(value = "/update.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "修改样机信息",
            notes = "修改样机信息 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "", dataType = "String", paramType = "body")
    public void update(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject obj = new JSONObject();
        obj.put("isOk", this.deviceSampleFacade.update(jsonData));
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(obj));
    }

    @ResponseBody
    @RequestMapping(value = "/getBrand.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "获取某人公司的品牌信息",
            notes = "获取某人公司的品牌信息 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "userId:''", dataType = "String", paramType = "body")
    public void getBrand(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> records = this.deviceSampleFacade.getBrand(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(records));
    }

    @ResponseBody
    @RequestMapping(value = "/getModel.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "根据品牌ID获取设备型号",
            notes = "根据品牌ID获取设备型号",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "brandId:''", dataType = "String", paramType = "body")
    public void getModel(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> records = this.deviceSampleFacade.getModel(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(records));
    }
    @RequestMapping(value = "/applyAudit.json", method = RequestMethod.POST)
    public void applyAudit(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = deviceSampleFacade.applyAudit(jsonData);
        boolean flag = Boolean.parseBoolean(result.getString("flag"));
        //发送消息
        sendMessage(result.getString("message"));
        if (flag) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond("审核成功"));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("审核驳回"));
        }
    }
    @ResponseBody
    @RequestMapping(value = "/selectStockList.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "库存报表",
            notes = "库存报表 ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "", dataType = "String", paramType = "body")
    public void selectStockList(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.deviceSampleFacade.selectStockList(jsonData);
        if (result!=null) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("未找到数据"));
        }
    }
    @RequestMapping(value = "/getDownStockList.json", method = RequestMethod.GET)
    public void getDownStockList(HttpServletResponse response,@RequestParam String userId,@RequestParam String type) throws Exception {
//导出表名、列名
        String title ="新机库存" ;
        String title1 ="旧机库存" ;
        String title2="置换房产" ;
        String[] rowsName = new String[]{"提车公司", "品牌", "库存地", "状态", "机型", "出厂日期",
                "斗容", "序列号", "备注"};
        String[] rowsName1 = new String[]{"提车公司", "品牌", "库存地", "状态", "机型", "出厂日期",
                "小时数", "序列号", "备注"};
        String[] rowsName2 = new String[]{"归属公司", "房屋名称", "房屋位置", "是否过户", "楼号、单元", "面积(平方米)", "备注", "", ""};
        String jsonData="{\"type\":\"" +type + "\",\"userId\":\"" + userId+ "\"}";
        JSONObject result=deviceSampleFacade.selectStockList(jsonData);
        List<JSONObject> newSample = (List<JSONObject>) net.sf.json.JSONArray.toCollection(net.sf.json.JSONArray.fromObject(result.getString("newSample")), JSONObject.class);
        List<JSONObject> oldSample = (List<JSONObject>) net.sf.json.JSONArray.toCollection(net.sf.json.JSONArray.fromObject(result.getString("oldSample")), JSONObject.class);
        List<JSONObject> oldHouse = (List<JSONObject>) net.sf.json.JSONArray.toCollection(net.sf.json.JSONArray.fromObject(result.getString("oldHouse")), JSONObject.class);
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        for (int i = 0; i < newSample.size(); i++) {
            JSONObject jsonObject = newSample.get(i);
            objs = new Object[rowsName.length];
            objs[0] = jsonObject.get("companyName");
            objs[1] = jsonObject.get("brandName");
            objs[2] = jsonObject.get("subStoreAddress");
            objs[3] = jsonObject.get("state");
            objs[4] = jsonObject.get("modelName");
            objs[5] = jsonObject.get("pickUpDate");
            objs[6] = jsonObject.get("bucketType");
            objs[7] = jsonObject.get("sequence");
            objs[8] = jsonObject.get("remark");
            dataList.add(objs);
        }
        List<Object[]> dataList1 = new ArrayList<Object[]>();
        Object[] objs1 = null;
        for (int i = 0; i < oldSample.size(); i++) {
            JSONObject jsonObject = oldSample.get(i);
            objs1 = new Object[rowsName1.length];
            objs1[0] = jsonObject.get("companyName");
            objs1[1] = jsonObject.get("brandName");
            objs1[2] = jsonObject.get("subStoreAddress");
            objs1[3] = jsonObject.get("state");
            objs1[4] = jsonObject.get("modelName");
            objs1[5] = jsonObject.get("factoryDate");
            objs1[6] = jsonObject.get("hours");
            objs1[7] = jsonObject.get("sequence");
            objs1[8] = jsonObject.get("remark");
            dataList1.add(objs1);
        }
        List<Object[]> dataList2 = new ArrayList<Object[]>();
        Object[] objs2 = null;
        for (int i = 0; i < oldHouse.size(); i++) {
            JSONObject jsonObject = oldHouse.get(i);
            objs2 = new Object[rowsName2.length+2];
            objs2[0] = jsonObject.get("companyName");
            objs2[1] = jsonObject.get("houseName");
            objs2[2] = jsonObject.get("houseAddress");
            objs2[3] = jsonObject.get("transfer");
            objs2[4] = jsonObject.get("buildingNumber");
            objs2[5] = jsonObject.get("area");
            objs2[6] = jsonObject.get("remark");
            objs2[7] = "";
            objs2[8] = "";
            dataList2.add(objs2);
        }
        ExportStockListExcel ex = new ExportStockListExcel(title,title1,title2,rowsName,rowsName1,rowsName2, dataList,dataList1,dataList2, response);
        ex.export();
    }
    public static String matchResult(Pattern p, String str)
    {
        StringBuilder sb = new StringBuilder();
        Matcher m = p.matcher(str);
        while (m.find())
            for (int i = 0; i <= m.groupCount(); i++)
            {
                sb.append(m.group());
            }
        return sb.toString();
    }

    @RequestMapping(value = "/getDownByCondition.json", method = RequestMethod.GET)
    public void getDownByCondition(HttpServletResponse response,@RequestParam String jsonData) throws Exception {
        //导出表名、列名
        String[] parmas = jsonData.split(",");
        List<String> row=new ArrayList<String>();
        List<String> data=new ArrayList<String>();
        for(int i=0;i<parmas.length;i++){
            String regEx1 = "[\\u4e00-\\u9fa5]";
            //String regEx2 = "[a-z||A-Z]";
            String regEx3 = "[0-9]";
            String str = parmas[i];
            String s1 = matchResult(Pattern.compile(regEx1),str);
            //String s2 = matchResult(Pattern.compile(regEx2),str);
            String s3 = matchResult(Pattern.compile(regEx3),str);
            //System.out.println(s1+"\n"+s2+"\n"+s3);
            row.add(s1);
            data.add(s3);
        }
        String[] rowsName=new String[row.size()];
        row.toArray(rowsName);//获得列名转换为数组;
        String title = "新机信息";
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        Object[] objs1=null;
        List<JSONObject> jsonObjectList=deviceSampleFacade.getDownByCondition();

        for (int i = 0; i < jsonObjectList.size(); i++) {
            JSONObject jsonObject = jsonObjectList.get(i);
            objs = new Object[51];
            objs[0] = jsonObject.get("companyName");
            objs[1] = jsonObject.get("brandName");
            objs[2] = jsonObject.get("deviceTypeName");
            objs[3] = jsonObject.get("modelName");
            objs[4] = jsonObject.get("sequence");
            objs[5] = jsonObject.get("tonConfig")+"吨";
            objs[6] = jsonObject.get("bucketType");
            objs[7] = jsonObject.get("productionDate");
            objs[8] = jsonObject.get("namePlateAttachName");
            objs[9] = jsonObject.get("stockTime");
            objs[10] = jsonObject.get("storeDuration")+"天";
            objs[11] = jsonObject.get("state");
            objs[12] = jsonObject.get("storeAddress");
            objs[13] = jsonObject.get("actualDeliveryDate");
            objs[14] = jsonObject.get("financing");
            objs[15] = jsonObject.get("pickUpDate");
            objs[16] = jsonObject.get("pickupPrice");
            objs[17] = jsonObject.get("partsName");
            objs[18] = jsonObject.get("invoiceAttachName");
            objs[19] = jsonObject.get("certificationAttachName");
            objs[20] = jsonObject.get("payment");
            objs[21] = jsonObject.get("freeMaturityDate");
            objs[22] = jsonObject.get("paymentDate");
            objs[23] = jsonObject.get("payee");
            objs[24] = jsonObject.get("paymentMoney");
            objs[25] = jsonObject.get("settle");
            objs[26] = jsonObject.get("trafficStarting");
            objs[27] = jsonObject.get("trafficDestination");
            objs[28] = jsonObject.get("transportCompany");
            objs[29] = jsonObject.get("transportStartTime");
            objs[30] = jsonObject.get("transportEndTime");
            objs[31] = jsonObject.get("specialFee");
            objs[32] = jsonObject.get("deductionFee");
            objs[33] = jsonObject.get("deductionRemark");
            objs[34] = jsonObject.get("drayLicense");
            objs[35] = jsonObject.get("driverName");
            objs[36] = jsonObject.get("driverTel");
            objs[37] = jsonObject.get("outType");
            objs[38] = jsonObject.get("contractNo");
            objs[39] = jsonObject.get("pickUpAddress");
            objs[40] = jsonObject.get("delivery_address");
            objs[41] = jsonObject.get("outTransportCompany");
            objs[42] = jsonObject.get("outTransportStartTime");
            objs[43] = jsonObject.get("outTransportEndTime");
            objs[44] = jsonObject.get("outSpecialFee");
            objs[45] = jsonObject.get("outDeductionFee");
            objs[46] = jsonObject.get("outDeductionRemark");
            objs[47] = jsonObject.get("outDrayLicense");
            objs[48] = jsonObject.get("outDriverName");
            objs[49] = jsonObject.get("outDriverTel");
            objs[50] = jsonObject.get("remark");
            dataList.add(objs);
        }
        /**
         * 如果添加字段，请对好顺序。懒得改了
         */
        //插数据
        List<Object[]> newDataList = new ArrayList<Object[]>();
        for(int a=0;a<dataList.size();a++){
            objs1 = new Object[data.size()];
            for(int j=0;j<data.size();j++){
                objs1[j]=dataList.get(a)[Integer.parseInt(data.get(j))];
            }
            newDataList.add(objs1);
        }


        ExportExcel ex = new ExportExcel(title, rowsName, newDataList, response);
        ex.export();
    }

    private void sendMessage(String jsonData) {
        List<JSONObject> jsonObjectList = null;
        if (!org.apache.commons.lang3.StringUtils.isBlank(jsonData)) {
            jsonObjectList = FastJsonConvert.convertJSONToArray(jsonData, JSONObject.class);
        }
        if (null != jsonObjectList && jsonObjectList.size() > 0) {
            TextMessage textMessage = new TextMessage(BaseUtils.succsessArrHourTimeRespond(jsonObjectList), true);
            try {
                myWebSocketHandler.sendMsgToAllUsers(textMessage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
